﻿using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;

namespace FCRE
{
    class PubVar
    {
        public static string uctepath = "";
        public static string dburl = "10.1.1.48";//"192.168.31.178";//
        public static string dbport = "3066";//"3306";//
        public static string dbpwd = "ucte2015";//
        public static string dburl1 = "10.1.1.48";//"192.168.31.178";//
        public static string dbport1 = "3066";//"3306";//
        public static string dbpwd1 = "ucte2015";//
        public static string webport = "8008";
        public static string ksweb = "";
        public static string ksweb2 = "";
        //IE或Email
        #region
        public static string OE_id="";
        public static string netAfile="";
        /// <summary>
        /// Email
        /// </summary>
        public static int OEflag = 0;
        public static string OutmailCcaddr = "";
        public static bool EmailCRAnnBoo = false;
        public static bool EmailForwardBoo = false;
        public static bool EmailFRBoo = false;
        public static string EmailKey = "";
        public static string OutmailAttachfn = "";
        public static string EmailRAnName1 = "";
        public static string EmailRAnName2 = "";
        public static string EmailRAnName3 = "";
        public static string OutmailText = "";
        public static bool EmailReadBoo = false;
        public static string OutmailSubject = "";
        public static string OutmailToaddr = "";
        public static bool EmailOuted = false;
        public static bool EmailIned = false;
        public static bool SaveWebBoolean = false;
        public static string AttachSaveAddr = "";
        public static string AttachDir = System.Windows.Forms.Application.StartupPath + @"\Res\";//附件原存地
        public static bool AttachSaved = false;
        public static bool StrEmailCoding = false;
        public static string InmailFromaddr = "";
        public static string InmailAttachfn = "";
        public static string StrEmailRAnName2 = "";
        public static string InmailText = "";
        public static string InmailSubject = "";
        public static string InmailToaddr = "";
        public static string InmailTime = "";
        /// <summary>
        /// IE Net
        /// </summary>
        public static int IEflag = 0;
        public static bool FindWebBoolean = false;
        public static string WebAddess = "";
        public static string WebCiKey = "";
        public static string WebFindKey = "";
        public static string WebFindName = "";
        public static string WebKeyword = "";
        public static bool WebOpenBoolean = false;
        public static string WebOpenName = "";
        public static string WebSaveName = "";
        #endregion
        public static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        public static string EncryptKey = "UCTE2015";//定义8bit密钥
        public static string rpwd = "gbnTzb9YQ9irwGaalbqmbA==";
        public static string lpwd = "k55lJGT6Aw2+mPQsx6jOmw==";
        public static string zpwd = "CC0+NfUpcbTi0pECGNfTAA==";
        public static string rurl = "qEEDNsZWILRVjhkuvorhdw==";// "XhCZkLXODDhoa+LWqQdUsg==";
        /// <summary>
        /// 路径
        /// </summary>
        public static string TestFolder;
        public static string ksroot;
        public static string batpath = "D:\\testucte.bat";
        public static bool jjed = false;//交卷完成
        public static string uid = "";
        public static string pwd = "";
        public static string pwd2 = "";
        public static string dblink = "";

        /////////////////////////////////////////
        /////   公用方法     ///////////////////
        ////////////////////////////////////////////
        #region
        [DllImport("cppJudge.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int cppJudge(int sid, string uid);
        /// <summary>
        /// 0正常可用，1异常不可用
        /// </summary>
        /// <returns></returns>
        [DllImport("cppJudge.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public static extern int gccTest();

        /// <summary>
        /// 局域网IP地址用于限制异地登录
        /// </summary>
        /// <returns></returns>
        public static string GetIpv4()//
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection nics = mc.GetInstances();
            foreach (ManagementObject nic in nics)
            {
                if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                {
                    return (nic["IPAddress"] as String[])[0];
                }
            }
            return null;
        }
        public static string[] GetLocalIpv4()
        {
            //事先不知道ip的个数，数组长度未知，因此用StringCollection储存
            try
            {
                IPAddress[] localIPs;
                localIPs = Dns.GetHostAddresses(Dns.GetHostName());
                StringCollection IpCollection = new StringCollection();
                foreach (IPAddress ip in localIPs)
                {
                    //根据AddressFamily判断是否为ipv4,如果是InterNetWork则为ipv6
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                        IpCollection.Add(ip.ToString());
                }
                string[] IpArray = new string[IpCollection.Count];
                IpCollection.CopyTo(IpArray, 0);
                return IpArray;
            }

            catch (Exception ex)
            {
                //LogHelper.
                //MessageBox.Show("Error: " + ex.Message);
                
            }
            return null;
        }

        /// <summary>  
        /// 通过DOS命令获得MAC地址  
        /// </summary>  
        /// <returns></returns>  
        public static string GetMac2()
        {
            string macAddress = "";
            Process p = null;
            StreamReader reader = null;
            try
            {
                ProcessStartInfo start = new ProcessStartInfo("cmd.exe");

                start.FileName = "ipconfig";
                start.Arguments = "/all";

                start.CreateNoWindow = true;

                start.RedirectStandardOutput = true;

                start.RedirectStandardInput = true;

                start.UseShellExecute = false;

                p = Process.Start(start);

                reader = p.StandardOutput;

                string line = reader.ReadLine();

                while (!reader.EndOfStream)
                {
                    if (line.ToLower().IndexOf("physical address") > 0 || line.ToLower().IndexOf("物理地址") > 0)
                    {
                        int index = line.IndexOf(":");
                        index += 2;
                        macAddress = line.Substring(index);
                        macAddress = macAddress.Replace('-', ':');
                        break;
                    }
                    line = reader.ReadLine();
                }
            }
            catch
            {

            }
            finally
            {
                if (p != null)
                {
                    p.WaitForExit();
                    p.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return macAddress;
        }
        /// <summary>
        /// Mac地址用于限制异地登录
        /// </summary>
        /// <returns></returns>
        public static string GetMac()//
        {
            string mac = "";
            try
            {
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection nics = mc.GetInstances();
                foreach (ManagementObject nic in nics)
                {
                    if ((bool)nic["IPEnabled"])
                    {
                        return mac = nic["MacAddress"].ToString();
                    }
                }
            }
            catch (Exception e)
            {
            }
            return null;
        }
        /// <summary>
        /// 远程开机，网卡需要具备远程唤醒功能
        /// BIOS设置“Wake up on LAN”项或“Wake on PCI Card”项均为“Enable”，启用该计算机的远程唤醒功能
        /// </summary>
        /// <param name="mac">MAC地址分配到mac数组中byte[] mac = new byte[6];mac[0] = 0x00;...</param>
        public static void WakeUp(byte[] mac)
        {
            UdpClient client = new UdpClient();
            client.Connect(IPAddress.Broadcast, 9090);
            //Magic Packet:连续6个字节的“FF”和连续重复16次的MAC地址
            byte[] packet = new byte[17 * 6];

            for (int i = 0; i < 6; i++)
                packet[i] = 0xFF;

            for (int i = 1; i <= 16; i++)
                for (int j = 0; j < 6; j++)
                    packet[i * 6 + j] = mac[j];

            int result = client.Send(packet, packet.Length);
        }
        /// <summary>
        /// 通过ping检测局域网是否连通
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool NetIsOK(string ip)
        {
            try
            {
                Ping ping = new Ping();
                PingReply pr = ping.Send(ip);
                if (pr.Status == IPStatus.Success) return true;
                else return false;
            }
            catch (Exception)//如果连接有异常，表示无法连接到服务器
            {
                return false;
            }
        }
		/// <summary>
        /// 通过HttpWebRequest检测网站是否提供服务
        /// </summary>
        /// <param name="ip">服务器地址或域名</param>
        /// <returns></returns>
		public static bool NetIsOK2(string ip)
		{
            //try{
            //             //解决握手失败，请求头域类型不匹配：HTTP1.1 HTTP1.0
            //             ServicePointManager.Expect100Continue = false;
            //             //地址
            //             string url = ip;
            //	//传的参数
            //	string datastr1 = "aaa";
            //	//转成字节
            //	byte[] bytearray1 = Encoding.UTF8.GetBytes(datastr1);
            //	//创建WebRequest
            //	HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
            //	//POST方式
            //	webrequest.Method = "POST";
            //	// <form encType=””>中默认的encType，form表单数据被编码为key/value格式发送到服务器（表单默认的提交数据的格式）
            //	webrequest.ContentType = "application/x-www-form-urlencoded";
            //	//获取字节数
            //	webrequest.ContentLength = Encoding.UTF8.GetByteCount(datastr1);
            //	//获取用于写入请求数据的 System.IO.Stream 对象
            //	Stream webstream = webrequest.GetRequestStream();
            //	//向当前流中写入字节序列，并将此流中的当前位置提升写入的字节数。
            //	webstream.Write(bytearray1, 0, bytearray1.Length);
            //	//获取返回数据
            //	HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
            //	//转码
            //	StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            //	//返回的结果
            //	string ret = sr.ReadToEnd();
            //	//关闭
            //	sr.Close();
            //	response.Close();
            //	webstream.Close();
            //	return true;
            //}
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ip);
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    resp.Close();
                    return true;
                }
            }
            catch (WebException e)//如果连接有异常，表示无法连接到服务器
			{
                return false;
			}
            return false;
		}
        /// <summary>
        /// 保存考生的网络、邮件题答案
        /// </summary>
        public static void saveNet()
        {
            //if(!File.Exists(netAfile))File.Create(netAfile);
            string[] netstr = new string[35];
            netstr[0] = EncryptDES(AttachSaveAddr);
            netstr[1] = EncryptDES(AttachSaved.ToString());
            netstr[2] = EncryptDES(EmailCRAnnBoo.ToString());
            netstr[3] = EncryptDES(EmailForwardBoo.ToString());
            netstr[4] = EncryptDES(EmailFRBoo.ToString());
            netstr[5] = EncryptDES(EmailIned.ToString());
            netstr[6] = EncryptDES(EmailKey);
            netstr[7] = EncryptDES(EmailOuted.ToString());
            netstr[8] = EncryptDES(EmailRAnName1);
            netstr[9] = EncryptDES(EmailRAnName2);
            netstr[10] = EncryptDES(EmailRAnName3);
            netstr[11] = EncryptDES(EmailReadBoo.ToString());
            netstr[12] = EncryptDES(FindWebBoolean.ToString());
            netstr[13] = EncryptDES(InmailAttachfn);
            netstr[14] = EncryptDES(InmailFromaddr);
            netstr[15] = EncryptDES(InmailSubject);
            netstr[16] = EncryptDES(InmailText);
            netstr[17] = EncryptDES(InmailTime);
            netstr[18] = EncryptDES(InmailToaddr);
            netstr[19] = EncryptDES(OutmailAttachfn);
            netstr[20] = EncryptDES(OutmailCcaddr);
            netstr[21] = EncryptDES(OutmailSubject);
            netstr[22] = EncryptDES(OutmailText);
            netstr[23] = EncryptDES(OutmailToaddr);
            netstr[24] = EncryptDES(SaveWebBoolean.ToString());
            netstr[25] = EncryptDES(StrEmailCoding.ToString());
            netstr[26] = EncryptDES(StrEmailRAnName2);
            netstr[27] = EncryptDES(WebAddess);
            netstr[28] = EncryptDES(WebCiKey);
            netstr[29] = EncryptDES(WebFindKey);
            netstr[30] = EncryptDES(WebFindName);
            netstr[31] = EncryptDES(WebKeyword);
            netstr[32] = EncryptDES(WebOpenBoolean.ToString());
            netstr[33] = EncryptDES(WebOpenName);
            netstr[34] = EncryptDES(WebSaveName);
            File.WriteAllLines(netAfile, netstr);
        }
        /// <summary>
        /// 读入考生的网络、邮件题答案，作为判题用
        /// </summary>
        public static void readNet()
        {
            if (!File.Exists(netAfile)) return;
            string[] netstr = File.ReadAllLines(netAfile);
            if (netstr.Length < 35) return;
            AttachSaveAddr = DecryptDES(netstr[0]);
            AttachSaved = Convert.ToBoolean(DecryptDES(netstr[1]));
            EmailCRAnnBoo = Convert.ToBoolean(DecryptDES(netstr[2]));
            EmailForwardBoo = Convert.ToBoolean(DecryptDES(netstr[3]));
            EmailFRBoo = Convert.ToBoolean(DecryptDES(netstr[4]));
            EmailIned = Convert.ToBoolean(DecryptDES(netstr[5]));
            EmailKey = DecryptDES(netstr[6]);
            EmailOuted = Convert.ToBoolean(DecryptDES(netstr[7]));
            EmailRAnName1 = DecryptDES(netstr[8]);
            EmailRAnName2 = DecryptDES(netstr[9]);
            EmailRAnName3 = DecryptDES(netstr[10]);
            EmailReadBoo = Convert.ToBoolean(DecryptDES(netstr[11]));
            FindWebBoolean = Convert.ToBoolean(DecryptDES(netstr[12]));
            InmailAttachfn = DecryptDES(netstr[13]);
            InmailFromaddr = DecryptDES(netstr[14]);
            InmailSubject = DecryptDES(netstr[15]);
            InmailText = DecryptDES(netstr[16]);
            InmailTime = DecryptDES(netstr[17]);
            InmailToaddr = DecryptDES(netstr[18]);
            OutmailAttachfn = DecryptDES(netstr[19]);
            OutmailCcaddr = DecryptDES(netstr[20]);
            OutmailSubject = DecryptDES(netstr[21]);
            OutmailText = DecryptDES(netstr[22]);
            OutmailToaddr = DecryptDES(netstr[23]);
            SaveWebBoolean = Convert.ToBoolean(DecryptDES(netstr[24]));
            StrEmailCoding = Convert.ToBoolean(DecryptDES(netstr[25]));
            StrEmailRAnName2 = DecryptDES(netstr[26]);
            WebAddess = DecryptDES(netstr[27]);
            WebCiKey = DecryptDES(netstr[28]);
            WebFindKey = DecryptDES(netstr[29]);
            WebFindName = DecryptDES(netstr[30]);
            WebKeyword = DecryptDES(netstr[31]);
            WebOpenBoolean = Convert.ToBoolean(DecryptDES(netstr[32]));
            WebOpenName = DecryptDES(netstr[33]);
            WebSaveName = DecryptDES(netstr[34]);

        }

        /// <summary>  
        /// 执行DOS命令，返回DOS命令的输出  
        /// </summary>  
        /// <param name="Command">dos命令</param>  
        /// <param name="milliseconds">等待命令执行的时间（单位：毫秒），  
        /// 如果设定为0，则无限等待</param>  
        /// <returns>返回DOS命令的输出</returns>  
        public static string cmdExcute(string command, int milliseconds)
        {
            string output = ""; //输出字符串
            int seconds = milliseconds * 1000;//转换为单位:秒  
            if (command != null && !command.Equals(""))
            {
                Process process = new Process();//创建进程对象  
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = "cmd.exe";//设定需要执行的命令  
                startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出  
                startInfo.UseShellExecute = false;//不使用系统外壳程序启动  
                startInfo.RedirectStandardInput = false;//不重定向输入  
                startInfo.RedirectStandardOutput = true; //重定向输出  
                startInfo.CreateNoWindow = true;//不创建窗口  
                process.StartInfo = startInfo;
                try
                {
                    if (process.Start())//开始进程  
                    {
                        if (seconds == 0)
                        {
                            process.WaitForExit();//这里无限等待进程结束  
                        }
                        else
                        {
                            process.WaitForExit(seconds); //等待进程结束，等待时间为指定的毫秒  
                        }
                        output = process.StandardOutput.ReadToEnd();//读取进程的输出  
                    }
                }
                catch
                {
                }
                finally
                {
                    if (process != null)
                        process.Close();
                }
            }
            return output;
        }
        /// <summary>  
        /// 执行bat处理，多条DOS命令  
        /// </summary>  
        /// <param name="Commands">dos命令</param>  
        /// 如果设定为0，则无限等待</param>  
        /// <returns>返回DOS命令的输出</returns>  
        public static void batExcute(string[] commands)
        {
            writeBATFile(commands);
            Process proc = null;
            try
            {
                proc = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = batpath;
                //startInfo.Arguments = string.Format("10");//this is argument
                //运行时隐藏dos窗口，需使用下面的代码
                startInfo.UseShellExecute = false;
                startInfo.CreateNoWindow = true;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;//这里设置DOS窗口不显示，经实践可行
                proc.StartInfo = startInfo;
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }
            finally
            {
                if (proc != null)
                    proc.Close();
            }
        }
        /// <summary>
        /// 把多条dos命令写成bat文件
        /// </summary>
        /// <param name="fileContent"></param>
        public static void writeBATFile(string[] fileContent)
        {
            int cmdn = fileContent.Length;
            if (!File.Exists(batpath))
            {
                FileStream fs1 = new FileStream(batpath, FileMode.Create, FileAccess.Write);//创建写入文件
                StreamWriter sw = new StreamWriter(fs1);
                for (int i = 0; i < cmdn; i++)
                {
                    sw.WriteLine(fileContent[i]);//开始写入值
                }
                sw.Close();
                fs1.Close();
            }
            else
            {
                FileStream fs = new FileStream(batpath, FileMode.Open, FileAccess.Write);
                StreamWriter sr = new StreamWriter(fs);
                for (int i = 0; i < cmdn; i++)
                {
                    sr.WriteLine(fileContent[i]);//开始写入值
                }
                sr.Close();
                fs.Close();
            }
        }
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <returns></returns>
        public static string EncryptDES(string encryptString)
        {
            if (encryptString.Length <= 0) return "";
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString"></param>
        /// <param name="decryptKey"></param>
        /// <returns></returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            if (decryptString.Length <= 0) return "";
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception e)
            {
                return decryptString;
            }
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString"></param>
        /// <param name="decryptKey"></param>
        /// <returns></returns>
        public static string DecryptDES(string decryptString)
        {
            if (decryptString.Length <= 0) return "";
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception e)
            {
                return decryptString;
            }
        }
        /// <summary>
        /// 递归删除所有目录及文件
        /// </summary>
        /// <param name="dPath"></param>
        public static void DelDirectory(string dPath)//
        {
            DirectoryInfo info = new DirectoryInfo(dPath);
            foreach (FileInfo info2 in info.GetFiles())
            {
                info2.Attributes = info2.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
                info2.Delete();
            }
            foreach (DirectoryInfo info3 in info.GetDirectories())
            {
                DelDirectory(info3.FullName);
                info3.Attributes = info3.Attributes & ~(FileAttributes.Archive | FileAttributes.ReadOnly | FileAttributes.Hidden);
                info3.Delete();
            }
        }

        public static string getFname(string fpath)//从路径中取文件名
        {
            return fpath.Substring(fpath.LastIndexOf(@"\") + 1).ToLower();//, (fpath.Length - fpath.LastIndexOf(@"\")) - 1
        }
        public static string getFdir(string fpath)//从路径中取文件目录
        {
            return fpath.Substring(0, fpath.LastIndexOf(@"\") + 1).ToLower();
        }

        #endregion
    }
}
